package servlet.news;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jdbc.DBUtils;
import model.News;
import model.NewsChannel;

@WebServlet("/NewsGetServlet")
public class NewsGetServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Connection connection = DBUtils.getConn();
		try {
			 String id  = request.getParameter("id");
			 id = new String(id.getBytes("iso-8859-1"),"utf-8");
			PreparedStatement ps = connection.prepareStatement("SELECT * from news where id=?");
			PreparedStatement pses = connection.prepareStatement("select * from news_channel");
			ps.setInt(1, Integer.valueOf(id));
			ResultSet rs = ps.executeQuery();
			ResultSet rses = pses.executeQuery();
			
			List<NewsChannel> newsChannellist = new ArrayList<>();
			while (rses.next()) {
				NewsChannel newsChannel = new NewsChannel();
				newsChannel.setId(rses.getInt("id"));
				newsChannel.setName(rses.getString("name"));
				newsChannellist.add(newsChannel);
			}
			News news = new News();
			while (rs.next()) {
				
				news.setId(rs.getInt("id"));
				news.setChannelId(rs.getInt("channel_id"));
				news.setLinktype(rs.getInt("linkType"));
				news.setLinkurl(rs.getString("linkurl"));
				news.setTitle(rs.getString("title"));
				news.setContent(rs.getString("content"));
				news.setAddtime(rs.getDate("addtime"));
			}
		
		request.setAttribute("news", news);
		request.setAttribute("newsChannellist", newsChannellist);	
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		
		request.getRequestDispatcher("set.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}


